package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os/exec"
	"time"

	"github.com/gorilla/websocket"
)

type CommandClass int

const (
	ShutDown CommandClass = iota
	Sleep
	ConstantSleep
	Restart
	MemLinkCode
	ShowMsg
)

type ExecCommand struct {
	Status  int          `json:"status"`
	Msg     string       `json:"msg"`
	Code    string       `json:"code"`
	Command CommandClass `json:"command"`
}

func main() {
	// 建立WebSocket连接
	conn, _, err := websocket.DefaultDialer.Dial("ws://8.130.75.98:81/remote_mini_service/options/execside/ws", nil)
	if err != nil {
		log.Fatal("Dial error:", err)
	}
	defer conn.Close()

	// err := conn.SetReadDeadline(60 * time.Second)
	// if err != nil {
	// 	log.Fatal("func SetReadDeadline failed")
	// }

	// conn.SetPongHandler(pongMessageProc)
	// conn.SetPingHandler(pongMessageProc)

	fmt.Printf("remoter server linked, listen command...\n")

	var clientCode string

	for {
		// 读取服务器的响应消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Fatal("Read error:", err)
		}

		// fmt.Println("Received message:", string(message))

		var execCmd ExecCommand
		err = json.Unmarshal(message, &execCmd)
		if err != nil {
			fmt.Printf("json unmarshal failed, %v", string(message))
			continue
		}

		switch execCmd.Command {
		case ShutDown:
			cmd := exec.Command("shutdown /p")
			err := cmd.Run()
			if err != nil {
				fmt.Println("命令执行出错:", err)
				continue
			}

		case Sleep:
			cmd := exec.Command("rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0")
			err := cmd.Run()
			if err != nil {
				fmt.Println("命令执行出错:", err)
				continue
			}

		case ConstantSleep:
			go constantSleep()

		case Restart:
			cmd := exec.Command("shutdown /r")
			err := cmd.Run()
			if err != nil {
				fmt.Println("命令执行出错:", err)
				continue
			}

		case MemLinkCode:
			clientCode = execCmd.Code
			fmt.Println("clientCode is: " + clientCode)

		case ShowMsg:
			fmt.Println("show msg: " + string(message))

		default:
			fmt.Println("reveive msg: " + string(message))
		}

	}

}

func constantSleep() {
	const heartbeatInterval = 8 * time.Second
	ticker := time.NewTicker(heartbeatInterval)
	defer ticker.Stop()

	for range ticker.C {
		cmd := exec.Command("rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0")
		err := cmd.Run()
		if err != nil {
			fmt.Println("命令执行出错:", err)
			continue
		}
	}
}

// func pongMessageProc(data string) error {
// 	fmt.Printf("Received Ping msg :%v\n", data)
// 	return nil
// }
